package com.atguigu.guli.service.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.guli.service.oss.service.FileService;
import com.atguigu.guli.service.oss.util.OSSProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    OSSProperties ossProperties;

    /**
     * 文件长传
     * @param inputStream 流
     * @param module 模块名
     * @param oFilename 文件名
     * @return 返回图片url地址
     */
    @Override
    public String upload(InputStream inputStream, String module, String oFilename) {
        String endPoint = ossProperties.getEndPoint();
        String keyId = ossProperties.getKeyId();
        String keySecret = ossProperties.getKeySecret();
        String bucketName = ossProperties.getBucketName();
        //判断oss实例是否存在：如果不存在则创建，如果存在则获取
        OSS ossClient = new OSSClientBuilder().build(endPoint, keyId, keySecret);
        if (!ossClient.doesBucketExist(bucketName)) {
            //创建bucket
            ossClient.createBucket(bucketName);
            //设置oss实例的访问权限：公共读
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }
        //返回的url路径 https://guli-file-xiaomingyuan.oss-cn-beijing.aliyuncs.com/avatar/d.jpg
        //构建日期路径：avatar/2019/02/26/文件名
        String folder = new DateTime().toString("yyyy/MM/dd");

        //文件名：uuid.扩展名
        String fileName = UUID.randomUUID().toString();
        //截取文件扩展名
        String fileExtension = oFilename.substring(oFilename.lastIndexOf("."));
        String key = module + "/" + folder + "/" + fileName + fileExtension;

        //文件上传至阿里云
        ossClient.putObject(ossProperties.getBucketName(), key, inputStream);

        //关闭ossClient
        ossClient.shutdown();

        //返回url地址
        return "https://" + bucketName + "." + endPoint + "/" + key;
    }

    /**
     * 根据文件地址删除oos中指定文件
     * @param url
     */
    @Override
    public void removeFile(String url) {
        String endPoint = ossProperties.getEndPoint();
        String keyId = ossProperties.getKeyId();
        String keySecret = ossProperties.getKeySecret();
        String bucketName = ossProperties.getBucketName();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, keyId, keySecret);

        String host = "https://" + bucketName + "." + endPoint + "/";
//        https://guli-file-xiaomingyuan.oss-cn-beijing.aliyuncs.com/avatar/2020/06/23/1c6d6f3a-5faf-4969-a4b0-78a5e88feebc.jpg
        // 文件名
        String objectName = url.substring(host.length());

        // 删除文件。
        ossClient.deleteObject(bucketName, objectName);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
